# -*- coding: utf-8 -*-
#
# @Author: CPS
# @email: 373704015@qq.com
# @Date: 2021-08-11 09:16:20.148313
# @Last Modified by: CPS
# @Last Modified time: 2021-08-11 09:16:20.148313
# @file_path "Z:\CPS\IDE\SublimeText\sublime_text_4113.21_win64_test\Data\Packages\testt_syntax_beautify\core"
# @Filename "update_channel_by_git.py"
# @Description: 功能描述
#


import os
from subprocess import Popen, PIPE
from tempfile import TemporaryDirectory
# from shutil import copy2


# options 一个对象 可以携带 strBuffer
def run_command(command:list, strBuffer:str=None, shell:bool=True, timeout=1000*10) -> str:
    try:
        p = Popen(
            command,
            stdout=PIPE,
            stdin=PIPE,
            stderr=PIPE,
            shell=shell)

        # 过来一遍 strBuffer
        if strBuffer != None:
            if isinstance(strBuffer, str):
                strBuffer = strBuffer.encode('utf-8')

        # 执行 command
        stdout, stderr = p.communicate(input=strBuffer, timeout=timeout)

        if stdout:
            return {"success":True,"res":stderr.decode('utf-8')}

        else:
            # print('没有返回有效的数据结果: \n%s' % stderr.decode('utf-8'))
            return {"success":False,"err":stderr.decode('utf-8')}

    except Exception:
        raise Exception('执行命令出错啦:', command)

def run(output:str, options:dict) -> dict:
    '''
    - Description 通过`git`仓库，拉取`channel_v3.json`
    - output {str} 最后`channel_v3.json`的存放处，绝对路径
    - options {dict}

    ```python
    options={
        "update_timeout":10000,     # 如果超过次时间，则放弃更新，单位ms
        "channel_v3_git_file": [
          "git@gitee.com:capsion/channelV3.git",
          "git@github.com:irvingcode/channelV3.git"
        ]
    }

    ```

    - returns {dict} 返回处理后的结果对象：


    ```ts
    interface returns { "success":booleen; "msg":string; "err":[string] }
    ```
    '''


    timeout = options['update_timeout'] if 'update_timeout' in options else 60*1000

    # 创建临时目录
    tmp_dir = TemporaryDirectory()

    return

    # 改变工作目录
    # work_dir = os.getcwd()
    os.chdir(tmp_dir.name)
    dirname:str = ""
    err_list=[]
    # 拉取git
    if isinstance(options['channel_v3_git_file'], list):
        for each_command in options['channel_v3_git_file']:
            print(['git','clone', '--depth=1', each_command])
            # try:
            #     res = run_command(['git','clone', '--depth=1', each_command], timeout=timeout)
            # except Exception as e:
            #     err_list.append(f'>>>拉取 {each_command} 失败<<<\n' + str(e))
            #     continue

            # if res['success']: 
            #     tar = os.path.realpath(each_command)
            #     dirname = os.path.basename().split('.')[0]
            #     break

            # 所有拉取都尝试过，失败后
            return {"success":False, "msg":"拉取仓库超时", "err":err_list}
                
    # 复制到插件目录
    channel_v3_file = f'{tmp_dir}/{dirname}/channel_v3.json'
    print('检验： ', channel_v3_file)
    if not os.path.exists(channel_v3_file):
        return {"success":False, "msg":"拉取channel_v3_file失败", "err":["文件不存在"]}

    # copy2(channel_v3_file, output)
    # return {"success":True, "msg":"拉取channel_v3_file成功", "err":err_list}


if ( __name__ == "__main__"):
    pass


